package acs.bridge.jreport;

import org.apache.log4j.Logger;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * acs.jreport.JReportSendMail
 * User: KuznetsovStV
 * Date: 24.12.11
 * Time: 11:23
 * Class for sending mail with report
 */
public class JReportSendMail extends JReportFileUse implements JReportSaveInterface {
    Logger logger = Logger.getLogger(this.getClass().getName());

    private JReportMailMessage templateMessage;
    private JavaMailSenderImpl mailSender;

    public void setTemplateMessage(SimpleMailMessage templateMessage) {
        this.templateMessage = (JReportMailMessage) templateMessage;
    }


    public void saveReport(byte[] data, String extension) throws IOException, MessagingException {

        /*     String fullFileName = getFullFileName(extension);

      byte[] outdata = archiveReport(data, fullFileName);

      fullFileName = getFullFileName((utilityArcInterface.getExtension() == null ? extension : utilityArcInterface.getExtension()));

      MimeMessage message = mailSender.createMimeMessage();
      MimeMessageHelper helper = new MimeMessageHelper(message, true);
      helper.setFrom(templateMessage.getFrom());
      helper.setTo(templateMessage.getTo());
      String l_subject = String.format(templateMessage.getSubject(), getReportName());
      helper.setSubject(l_subject);
      helper.setText(templateMessage.getText());

      // use the true flag to indicate the text included is HTML
      //  helper.setText("<html><body><img src='cid:001_Likard.jrxml'></body></html>", true);
      //FileSystemResource res = new FileSystemResource(new File("C:\\001_Likard.jrxml"));
      //helper.addAttachment("001_Likard.jrxml", res);

      fullFileName = getFullFileName((utilityArcInterface.getExtension() == null ? extension : utilityArcInterface.getExtension()));

      logger.info("Sending e-mail {filename=" + fullFileName + ",subject=" + l_subject + ",to=" + templateMessage.getTo()[0] + "}");
      helper.addAttachment(fullFileName,
              new ByteArrayResource(outdata));

      mailSender.send(message);  */
    }


    public void saveReportItem(Collection<JReportItem> jReportItemCollection) throws Exception {


        //String fullFileName = getFullFileName(jReportItem.getReportExt());

        //String fullFileName = getFullFileName(extension);

        byte[] outdata = archiveReport(jReportItemCollection);

        //fullFileName = getFullFileName((utilityArcInterface.getExtension() == null ? extension : utilityArcInterface.getExtension()));
        String fullFileName = getFullFileName(utilityArcInterface.getExtension());

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);


        templateMessage.setTemplate(getParameters());
        /*if (getParameters() != null) {
            Iterator it = getParameters().keySet().iterator();

            while (it.hasNext()) {
                String key = (String) it.next();
                if (key.equals("%templateMessageFrom%") && templateMessage.getFrom() == null)
                    templateMessage.setFrom(getParameters().getProperty(key));
                if (key.equals("%templateMessageTo%") && templateMessage.getTo() == null)
                    templateMessage.setTo(getParameters().getProperty(key));
                if (key.equals("%templateMessageSubject%") && templateMessage.getSubject() == null)
                    templateMessage.setSubject(getParameters().getProperty(key));
                if (key.equals("%templateMessageText%") && templateMessage.getText() == null)
                    templateMessage.setText(getParameters().getProperty(key));
            }
        }  */

        if (templateMessage.getFrom() != null)
            helper.setFrom(templateMessage.getFrom());
        if (templateMessage.getTo() != null) {

            List<InternetAddress> l_address = new ArrayList<InternetAddress>();
            for (int i = 0; i < templateMessage.getTo().length; i++) {
                InternetAddress[] l_adr = InternetAddress.parse(templateMessage.getTo()[i], true);
                for (int p = 0; p < l_adr.length; p++) {
                    l_address.add(l_adr[p]);
                }
            }


            helper.setTo((InternetAddress[]) l_address.toArray(new InternetAddress[l_address.size()]));
        }

        if (templateMessage.getSubject() != null) {
            String l_subject = String.format(templateMessage.getSubject(), getReportName());
            helper.setSubject(l_subject);
        }
        if (templateMessage.getText() != null)
            helper.setText(templateMessage.getText());


        // use the true flag to indicate the text included is HTML
        //  helper.setText("<html><body><img src='cid:001_Likard.jrxml'></body></html>", true);
        //FileSystemResource res = new FileSystemResource(new File("C:\\001_Likard.jrxml"));
        //helper.addAttachment("001_Likard.jrxml", res);

        //fullFileName = getFullFileName((utilityArcInterface.getExtension() == null ? extension : utilityArcInterface.getExtension()));

        logger.info("Sending e-mail {filename=" + fullFileName + ",subject=" + templateMessage.getSubject() + ",to=" + templateMessage.getTo()[0] + "}");
        helper.addAttachment(fullFileName,
                new ByteArrayResource(outdata));
        System.setProperty("mail.mime.multipart.ignoreexistingboundaryparameter", "true");
        mailSender.send(message);

    }

    public void setReportName(String reportName) {
        fileName = reportName;
    }

    public String getReportName() {
        return fileName;
    }

    public void setMailSender(JavaMailSenderImpl mailSender) {
        this.mailSender = mailSender;
    }
}
